/*
 * @(#)org.example.netty.tcp 2020/4/3/0003
 *
 * Copy Right@ 人人译视界
 */


package org.example.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/3/0003
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
	private int count = 1;
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
		System.out.println("服务器端接收数据length=：" + msg.getLength());
		System.out.println("服务器端接收数据content=：" + new String(msg.getContent(), Charset.forName("utf-8")));
		System.out.println("服务器接收到的数据包数量=" + count++);

		String str = UUID.randomUUID().toString();
		byte[] bytes = str.getBytes("utf-8");
		int response = bytes.length;
		MessageProtocol protocol = new MessageProtocol();
		protocol.setLength(response);
		protocol.setContent(bytes);
		ctx.channel().writeAndFlush(protocol);
	}
}
